#include <driver/uart.h>
#include "HardwareSerial.h"
#include <freertos/FreeRTOS.h>

HardwareSerial &Serial = HardwareSerial::getInstance();
void HardwareSerial::send(const std::string &str)
{
    uart_write_bytes(uart_num, str.c_str(), str.length());
}

void HardwareSerial::begin(int baud_rate)
{
    this->baud_rate = baud_rate;
    uart_driver_install(uart_num, uart_buffer_size, uart_buffer_size / 2, 0, NULL, 0);
}
void HardwareSerial::print(const std::string &str)
{
    send(str);
}
void HardwareSerial::println(const std::string &str)
{
    send(str + "\n");
}
bool HardwareSerial::available()
{
    size_t length = 0;
    uart_get_buffered_data_len(uart_num, &length);
    return length > 0;
}
char HardwareSerial::read()
{
    char c;
    uart_read_bytes(uart_num, &c, 1, 1000 / portTICK_PERIOD_MS);
    return c;
}
std::string HardwareSerial::readString()
{
    std::string str;
    size_t len = 0;
    uart_get_buffered_data_len(uart_num, &len);

    char *buf = (char *)malloc(len + 1);
    uart_read_bytes(uart_num, buf, len, 1000 / portTICK_PERIOD_MS);
    buf[len] = '\0';
    str = std::string(buf);
    free(buf);
    return str;
}
